import store from '@/store';
import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from '../views/Home.vue';
// import store from '@/store';
// 重复点击同一个路由会出现报错。
// 把这段代码直接粘贴到router/index.js中的Vue.use(VueRouter)之前
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch((err) => {});
};
Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
  },
  {
    path: '/goods',
    name: 'goods',
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/Goods.vue'),
  },
  {
    path: '/user',
    name: 'user',
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/User.vue'),
      redirect:'/user/cart',
    children: [
      { path: 'cart', component: () => import('../components/user/Cart.vue') },
    ],
    // 路由独享守卫
    // beforeEnter: (to, from, next) => {
    //   // 则需要获取是否存在token
    //   let token = localStorage.getItem('x-auth-token');
    //   if (token) {
    //     // 如果存在则正常进入界面
    //     next();
    //   } else {
    //     // 否则提示没有登录
    //     store.dispatch('showToast/asyncIsShowToast', {
    //       msg: '你还没有登录',
    //       type: 'warning',
    //     });
    //   }
    // },
  },
  {
    path: '/order',
    name: 'order',
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/Order.vue'),
  },
  {
    path: '/free',
    name: 'free',
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/Free.vue'),
  },
  {
    path: '/details',
    name: 'details',
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/Details.vue'),
  },
  {
    path: '*',
    name: 'error',
    component: () =>
      import(/* webpackChunkName: "about" */ '../views/Error.vue'),
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

// 导航守卫  全局导航守卫
// to:route:即将要进入的目标  from：route 当前导航正要离开的路由  next：function：一定要调用该方法来resolve 这个钩子
// router.beforeEach((to, from, next) => {
//   // 如果准备去user页面
//   if (to.path == '/user') {
//     // 则需要获取是否存在token
//     let token = localStorage.getItem('x-auth-token');
//     if (token) {
//       // 如果存在则正常进入界面
//       next();
//     } else {
//       // 否则提示没有登录
//       store.dispatch('showToast/asyncIsShowToast', {
//         msg: '你还没有登录',
//         type: 'waring',
//         // type: 'danger',
//       });
//     }
//     return; //预防代码执行下一个next
//   }
//   next();
// });
export default router;
